const jwe = require('jsonwebtoken')
const {Forbbiden} = require('../core/httpException')

class Auth {
  constructor(level) {
    Auth.level = level || 1
    Auth.USER = 8  // 普通用户
    Auth.ADMIN = 16  // 管理员
  }
  get m () {
    return async (ctx, next) => {
      let decode
      let errMsg = 'token不合法'
      const header = ctx.request.header
      const token = header.token
      if(!token) {
        throw new Forbbiden(errMsg)
      }

      try {
        decode = jwe.verify(token, global.config.security.secretKey)
      } catch (error) {
        if(error.name == 'TokenExpiredError') {
          errMsg = 'token已过期'
        }
        throw new Forbbiden(errMsg)
      }

      // 判断接口权限
      if(decode.scope < Auth.level) {
        errMsg = '权限不足'
        throw new Forbbiden(errMsg)
      }
      ctx.auth = {
        uid: decode.uid,
        scope: decode.scope
      }
      await next()
    }
  }
}

module.exports = {
  Auth
}

